package com.example.administrator.five_in_a_row;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MyService extends Service {
    private Handler handler=null;
    private boolean isColsed=false;
    private PrintWriter pw = null;
    private MyBinder binder = new MyBinder();
    public MyService() {
    }
    public class MyBinder extends Binder{
     public void sendData (String data){


     }
        public void sendHandler ( Handler handler){
            MyService.this. handler= handler;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            Socket client = new Socket("192.168.3.247",12345);

            InputStream is = client.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            OutputStream os = client.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw);

            while (!isColsed){
                String data = br.readLine();

                if (data == null){return;}
                if (null!= handler){

                    Message msg = new Message();
                    JSONObject jo = new JSONObject(data);
                    int cmd = jo.getInt("cmd");
                    switch (cmd){
                        case 1:
                            JSONArray ja = jo.getJSONArray("room_list");
                            msg.what = 0x123;
                            msg.obj = ja;

                            break;
                        default:
                            break;
                    }

                    handler.sendMessage(msg);
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @Override
    public IBinder onBind(Intent intent) {
      return binder;
    }
}
